<?php
declare (strict_types=1);

namespace app\command;

use app\common\business\Contract;
use app\common\business\DiseasePath;
use app\common\lib\Redis;
use app\common\lib\ZhyxBeanstalkd;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\CollectCase;
use app\common\model\CollectClass;
use app\common\model\PacketConfig;
use app\common\model\TimingTask;
use app\impl\SimpleFactory;
use catchAdmin\propaganda\service\EdCenterService;
use Pheanstalk\Exception\ClientException;
use Pheanstalk\Exception\ConnectionException;
use Pheanstalk\Exception\ServerException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\Log;

class AutoRunGroup extends Command
{


    protected function configure(): void
    {
        // 指令配置
        $this->setName('autoRunGroup')
            ->setDescription('自动分组');
    }

    /**
     * @throws \Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $data = $this->getSourceData();
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $output->writeln("开始同步{$v['group_name']}分组");
                $taskData = iterator_to_array($v["task_data"]);
               
                if ($taskData) {
                    $result = (new Contract())->grouping($taskData, $v["group_id"], 0, 1);
                    if ($result) {
                        (new TimingTask())->where([["id", "in",(array)$v["gid"]]])->save(["task_status" => 1]);
                    }
                }
                $output->writeln("分组{$v['group_name']}同步成功");
            }
        }

    }


    /**
     * 获取数据源
     * @return array
     */
    private function getSourceData(): array
    {
        $date = date("Y-m-d");
        $collection = (ZhyxMongo::getInstance())->setCollection('time_task');
        $cursor = $collection->aggregate([['$match' => ['task_plan_date' => $date, 'type' => 'join_group']], ['$group' => ['_id' => '$group_id', 'group_id' => ['$first' => '$group_id'], 'group_name' => ['$first' => '$group_name'], 'task_plan_date' => ['$first' => '$task_plan_date'], 'gid' => ['$push' => ['$toString' => '$_id']],'task_data' => ['$addToSet' => ['patient_uuid' => '$task_data.patient_uuid', 'patient_id' => '$task_data.patient_id', 'name' => '$task_data.patient_name', 'sex' => '$task_data.sex']]]]]);
        return iterator_to_array($cursor);
    }




}